import Foundation
import UIKit
import Combine

// MARK: - 地点分组服务
@MainActor
class LocationGroupService: ObservableObject {
    @Published var locationGroups: [LocationGroup] = []
    @Published var isLoading = false
    @Published var lastUpdateTime: Date = Date()
    
    // 缓存管理
    private var cachedGroups: [LocationGroup] = []
    private var lastPhotoCount = 0
    private var lastDataFingerprint = ""
    
    // 持久化
    private let locationGroupsKey = "LocationGroups"
    
    // 通知中心
    private var cancellables = Set<AnyCancellable>()
    
    // 🎯 优化：静态变量用于减少重复日志
    #if DEBUG
    private static var lastKnownCityCount = 0
    private static var lastUnknownCount = 0
    private static var lastUnknownCount2 = 0
    #endif
    
    init() {
        print("📍 [LocationGroupService] 初始化地点分组服务")
        setupNotifications()
    }
    
    deinit {
        cancellables.removeAll()
    }
    
    // MARK: - 公共接口
    
    /// 获取地点分组（主要接口）
    func getLocationGroups(from photos: [PhotoData]) -> [LocationGroup] {
        // 🚀 性能优化：减少分组计算日志
        let shouldLog = photos.count > 1000 // 只有大量照片才打印分组日志
        
        if shouldLog {
            print("📍 [LocationGroupService] 开始计算地点分组，照片数: \(photos.count)")
        }
        
        // 检查缓存
        if shouldUseCache(photos: photos) {
            if shouldLog {
                print("📍 [LocationGroupService] 使用缓存分组，数量: \(cachedGroups.count)")
            }
            return cachedGroups
        }
        
        // 重新计算分组
        let newGroups = calculateLocationGroups(from: photos)
        
        // 更新缓存
        updateCache(groups: newGroups, photos: photos)
        
        // 保存到持久化
        saveToPersistence(newGroups)
        
        // 更新UI
        DispatchQueue.main.async {
            self.locationGroups = newGroups
            self.lastUpdateTime = Date()
        }
        
        if shouldLog {
            print("📍 [LocationGroupService] 分组计算完成，数量: \(newGroups.count)")
        }
        return newGroups
    }
    
    /// 🚀 优化：直接加载持久化分组，避免重新计算
    func loadPersistentGroups() {
        let groupLoadStartTime = Date()
        print("🚀 [LocationGroupService] 开始加载持久化分组 - \(groupLoadStartTime)")
        
        guard let data = UserDefaults.standard.data(forKey: locationGroupsKey),
              let serializableGroups = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
            print("🚀 [LocationGroupService] 持久化分组数据为空")
            return
        }
        
        var loadedGroups: [LocationGroup] = []
        
        for groupData in serializableGroups {
            guard let id = groupData["id"] as? String,
                  let country = groupData["country"] as? String,
                  let city = groupData["city"] as? String,
                  let totalPhotos = groupData["totalPhotos"] as? Int,
                  let isParentNode = groupData["isParentNode"] as? Bool else {
                continue
            }
            
            let detailedLocation = groupData["detailedLocation"] as? String
            let parentId = groupData["parentId"] as? String
            
            // 创建分组（不包含照片数组，避免重复遍历）
            let locationGroup = LocationGroup(
                country: country,
                city: city,
                detailedLocation: detailedLocation?.isEmpty == false ? detailedLocation : nil,
                photos: [], // 照片数组会在需要时动态填充
                coverPhoto: nil,
                totalPhotos: totalPhotos,
                isParentNode: isParentNode,
                parentCity: parentId?.isEmpty == false ? city : nil
            )
            
            loadedGroups.append(locationGroup)
        }
        
        // 更新缓存和UI
        cachedGroups = loadedGroups
        lastPhotoCount = 0 // 标记为已加载持久化数据
        lastDataFingerprint = "persistent"
        
        DispatchQueue.main.async {
            self.locationGroups = loadedGroups
            self.lastUpdateTime = Date()
        }
        
        let groupLoadEndTime = Date()
        let groupLoadDuration = groupLoadEndTime.timeIntervalSince(groupLoadStartTime)
        print("🚀 [LocationGroupService] 持久化分组加载完成，数量: \(loadedGroups.count)")
        print("⏱️ 分组加载耗时: \(String(format: "%.2f", groupLoadDuration)) 秒")
    }
    
    /// 强制刷新分组
    func forceRefresh() {
        print("🔄 [LocationGroupService] 强制刷新分组")
        clearCache()
        NotificationCenter.default.post(name: NSNotification.Name("RefreshLocationAxis"), object: nil)
    }
    
    /// 强制刷新分组（内部方法）
    func forceRefreshInternal() {
        print("🔄 [LocationGroupService] 内部强制刷新分组")
        clearCache()
    }
    
    /// 清空所有分组缓存
    func clearAllGroups() {
        print("🗑️ [LocationGroupService] 清空所有分组缓存")
        clearCache()
        locationGroups = []
        NotificationCenter.default.post(name: NSNotification.Name("RefreshLocationAxis"), object: nil)
    }
    
    /// 迁移旧格式的持久化数据到新格式
    func migratePersistenceData() {
        print("🔄 [LocationGroupService] 开始迁移持久化数据格式")
        
        guard let data = UserDefaults.standard.data(forKey: locationGroupsKey),
              let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
            print("📍 没有找到需要迁移的数据")
            return
        }
        
        // 检查是否已经是新格式
        let hasNewFormat = jsonArray.contains { groupData in
            groupData["parentId"] != nil
        }
        
        if hasNewFormat {
            print("📍 数据已经是新格式，无需迁移")
            return
        }
        
        print("📍 检测到旧格式数据，开始迁移...")
        
        // 创建父节点ID映射
        var parentIdMap: [String: String] = [:]
        for groupData in jsonArray {
            if let isParentNode = groupData["isParentNode"] as? Bool, isParentNode,
               let id = groupData["id"] as? String,
               let city = groupData["city"] as? String {
                parentIdMap[city] = id
            }
        }
        
        // 转换为新格式
        let newFormatData = jsonArray.map { groupData in
            var newGroupData = groupData
            
            // 移除旧的parentCity字段
            newGroupData.removeValue(forKey: "parentCity")
            
            // 添加新的parentId字段
            if let isParentNode = groupData["isParentNode"] as? Bool, !isParentNode,
               let parentCity = groupData["parentCity"] as? String {
                newGroupData["parentId"] = parentIdMap[parentCity] ?? ""
            } else {
                newGroupData["parentId"] = ""
            }
            
            return newGroupData
        }
        
        // 保存新格式数据
        if let newData = try? JSONSerialization.data(withJSONObject: newFormatData) {
            UserDefaults.standard.set(newData, forKey: locationGroupsKey)
            print("✅ 数据迁移完成，新格式已保存")
        } else {
            print("❌ 数据迁移失败")
        }
    }
    
    /// 打印持久化数据
    func printPersistenceData() {
        print("📊 [LocationGroupService] 打印持久化数据")
        
        if let data = UserDefaults.standard.data(forKey: locationGroupsKey),
           let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
            
            print("📍 持久化数据详情:")
            print("   - 分组数量: \(jsonArray.count)")
            
            for (index, groupData) in jsonArray.enumerated() {
                let country = groupData["country"] as? String ?? "未知"
                let city = groupData["city"] as? String ?? "未知"
                let detailedLocation = groupData["detailedLocation"] as? String ?? ""
                let totalPhotos = groupData["totalPhotos"] as? Int ?? 0
                let isParentNode = groupData["isParentNode"] as? Bool ?? false
                let parentId = groupData["parentId"] as? String ?? ""
                let parentCity = groupData["parentCity"] as? String ?? ""
                
                print("   - 分组 \(index + 1):")
                print("     * 国家: \(country)")
                print("     * 城市: \(city)")
                print("     * 详细地址: \(detailedLocation)")
                print("     * 照片数: \(totalPhotos)")
                print("     * 是否父节点: \(isParentNode)")
                print("     * 父节点ID: \(parentId)")
                print("     * 父城市: \(parentCity)")
            }
        } else {
            print("📍 持久化数据: 无数据")
        }
    }
    
    /// 打印缓存数据
    func printCacheData() {
        print("📊 [LocationGroupService] 打印缓存数据")
        
        print("📍 缓存数据详情:")
        print("   - 缓存分组数量: \(cachedGroups.count)")
        print("   - 上次照片数量: \(lastPhotoCount)")
        print("   - 数据指纹: \(lastDataFingerprint)")
        
        if cachedGroups.isEmpty {
            print("   - 缓存状态: 空缓存")
        } else {
            print("   - 缓存状态: 有数据")
            for (index, group) in cachedGroups.enumerated() {
                print("   - 缓存分组 \(index + 1):")
                print("     * 国家: \(group.country)")
                print("     * 城市: \(group.city)")
                print("     * 详细地址: \(group.detailedLocation ?? "无")")
                print("     * 照片数: \(group.totalPhotos)")
                print("     * 是否父节点: \(group.isParentNode)")
                print("     * 父城市: \(group.parentCity ?? "无")")
            }
        }
    }
    
    /// 调试方法：打印当前分组状态
    func debugCurrentGroups(from photos: [PhotoData]) {
        print("🔍 [LocationGroupService] === 调试当前分组状态 ===")
        
        let groups = getLocationGroups(from: photos)
        print("🔍 总分组数: \(groups.count)")
        
        for (index, group) in groups.enumerated() {
            print("🔍 分组 \(index + 1):")
            print("   - 国家: \(group.country)")
            print("   - 城市: \(group.city)")
            print("   - 详细地址: \(group.detailedLocation ?? "无")")
            print("   - 照片数: \(group.totalPhotos)")
            print("   - 是否父节点: \(group.isParentNode)")
            
            if group.totalPhotos > 0 {
                print("   - 示例照片ID: \(group.photos.first?.id ?? "无")")
            }
        }
        
        print("🔍 === 调试完成 ===")
    }
    
    /// 调试方法：检查地理编码后的照片数据
    func debugGeocodedPhotoData(from photos: [PhotoData]) {
        print("🔍 [LocationGroupService] === 检查地理编码后的照片数据 ===")
        
        let geocodedPhotos = photos.filter { photo in
            guard let location = photo.location else { return false }
            return location.country != nil || location.city != nil || location.state != nil || location.address != nil
        }
        
        print("🔍 有地理信息的照片数: \(geocodedPhotos.count)")
        
        for (index, photo) in geocodedPhotos.prefix(10).enumerated() {
            guard let location = photo.location else { continue }
            
            print("🔍 照片 \(index + 1) (ID: \(photo.id)):")
            print("   - 国家: \(location.country ?? "nil")")
            print("   - 州/省: \(location.state ?? "nil")")
            print("   - 城市: \(location.city ?? "nil")")
            print("   - 地址: \(location.address ?? "nil")")
            print("   - 坐标: \(location.coordinate.latitude), \(location.coordinate.longitude)")
            print("   - 地理编码尝试: \(photo.hasGeocodingAttempted ?? false)")
            
            // 检查是否符合"已知城市"的条件
            let hasCountry = location.country != nil && location.country != "未知国家"
            let hasCity = location.city != nil && location.city != "未知城市"
            let hasState = location.state != nil && location.state != "未知州"
            
            print("   - 条件检查:")
            print("     * 有国家信息: \(hasCountry)")
            print("     * 有城市信息: \(hasCity)")
            print("     * 有州信息: \(hasState)")
            print("     * 符合已知城市条件: \(hasCountry && hasCity && hasState)")
            print("")
        }
        
        print("🔍 === 地理编码数据检查完成 ===")
    }
    
    /// 调试方法：详细分析数据指纹
    func debugDataFingerprint(from photos: [PhotoData]) {
        print("🔍 [LocationGroupService] === 详细分析数据指纹 ===")
        
        let photoCount = photos.count
        let photosWithLocation = photos.filter { $0.location != nil }.count
        let photosWithoutLocation = photos.filter { $0.location == nil }.count
        
        let photosWithCompleteLocation = photos.filter { photo in
            guard let location = photo.location else { return false }
            return (location.country != nil && location.country != "未知国家") &&
                   (location.city != nil && location.city != "未知城市") &&
                   (location.state != nil && location.state != "未知州")
        }.count
        
        let geocodedPhotos = photos.filter { $0.hasGeocodingAttempted == true }.count
        
        let photosWithAddress = photos.filter { photo in
            guard let location = photo.location else { return false }
            return location.address != nil && location.address != "未知" && location.address != "未知地点"
        }.count
        
        print("🔍 照片统计:")
        print("   - 总照片数: \(photoCount)")
        print("   - 有地理信息: \(photosWithLocation)")
        print("   - 无地理信息: \(photosWithoutLocation)")
        print("   - 完整地理信息: \(photosWithCompleteLocation)")
        print("   - 地理编码尝试: \(geocodedPhotos)")
        print("   - 有地址信息: \(photosWithAddress)")
        
        let fingerprint = calculateDataFingerprint(photos: photos)
        print("🔍 数据指纹: \(fingerprint)")
        
        print("🔍 === 数据指纹分析完成 ===")
    }
    
    // MARK: - 私有方法
    
    private func setupNotifications() {
        NotificationCenter.default.publisher(for: NSNotification.Name("PhotosUpdated"))
            .sink { [weak self] _ in
                self?.handlePhotosUpdate()
            }
            .store(in: &cancellables)
        
        // 🚀 新增：监听快速开机加载通知
        NotificationCenter.default.publisher(for: NSNotification.Name("LoadPersistentGroups"))
            .sink { [weak self] _ in
                self?.loadPersistentGroups()
            }
            .store(in: &cancellables)
        
        // 🚀 新增：监听批量解析完成通知，强制清除缓存
        NotificationCenter.default.publisher(for: NSNotification.Name("RefreshLocationAxis"))
            .sink { [weak self] _ in
                self?.clearCache()
                print("📍 [LocationGroupService] 收到刷新通知，已强制清除缓存")
            }
            .store(in: &cancellables)
    }
    
    private func handlePhotosUpdate() {
        print("📍 [LocationGroupService] 收到照片更新通知")
        clearCache()
    }
    
    private func shouldUseCache(photos: [PhotoData]) -> Bool {
        let currentFingerprint = calculateDataFingerprint(photos: photos)
        let shouldUse = lastPhotoCount == photos.count && 
                       !cachedGroups.isEmpty && 
                       currentFingerprint == lastDataFingerprint
        
        // 🚀 性能优化：减少缓存检查日志
        let shouldLog = photos.count > 1000 // 只有大量照片才打印缓存日志
        
        if shouldLog {
            print("📍 [LocationGroupService] 缓存检查: 照片数=\(photos.count), 缓存数=\(cachedGroups.count), 指纹匹配=\(currentFingerprint == lastDataFingerprint)")
            print("📍 [LocationGroupService] 当前指纹: \(currentFingerprint)")
            print("📍 [LocationGroupService] 上次指纹: \(lastDataFingerprint)")
            
            if currentFingerprint != lastDataFingerprint {
                print("📍 [LocationGroupService] 指纹不匹配，将重新计算分组")
            }
        }
        
        return shouldUse
    }
    
    private func calculateLocationGroups(from photos: [PhotoData]) -> [LocationGroup] {
        var groups: [LocationGroup] = []
        
        // 🎯 修复：正确分离已知城市和未知照片
        let knownCityPhotos = photos.filter { photo in
            guard let location = photo.location else { return false }
            // 成功解析的照片：有国家和城市信息，且不是"未知"值
            let hasCountry = location.country != nil && location.country != "未知国家" && location.country != "未知"
            let hasCity = location.city != nil && location.city != "未知城市" && location.city != "未知"
            let hasAddress = location.address != nil && location.address != "未知地点" && location.address != "未知"
            
            // 必须有国家和城市信息，地址信息可选
            return hasCountry && hasCity
        }
        
        let unknownPhotos = photos.filter { photo in
            // 没有位置信息
            guard let location = photo.location else { return true }
            
            // 🎯 修复：位置信息不完整（与批量解析逻辑保持一致）
            // 只检查国家和城市信息，地址信息可选
            let hasIncompleteCountry = location.country == nil || location.country == "未知国家" || location.country == "未知"
            let hasIncompleteCity = location.city == nil || location.city == "未知城市" || location.city == "未知"
            
            return hasIncompleteCountry || hasIncompleteCity
        }
        
        // 🎯 优化：减少重复日志，只在分组数量发生变化时打印
        #if DEBUG
        if knownCityPhotos.count != Self.lastKnownCityCount || unknownPhotos.count != Self.lastUnknownCount {
            print("📍 [LocationGroupService] 照片分类: 已知城市=\(knownCityPhotos.count), 未知照片=\(unknownPhotos.count)")
            Self.lastKnownCityCount = knownCityPhotos.count
            Self.lastUnknownCount = unknownPhotos.count
        }
        #endif
        
        // 处理已知城市的照片
        if !knownCityPhotos.isEmpty {
            let locationGroups = processKnownCityPhotos(knownCityPhotos)
            groups.append(contentsOf: locationGroups)
        }
        
        // 处理未知照片（全部归入"待识别照片"或"无法识别未知照片"）
        if !unknownPhotos.isEmpty {
            let unknownGroups = processPhotosWithoutLocation(unknownPhotos)
            groups.append(contentsOf: unknownGroups)
        }
        
        // 排序：待识别的照片优先显示在最上面
        groups.sort { group1, group2 in
            // 待识别的照片优先显示
            let isUnknown1 = group1.country == "待识别照片"
            let isUnknown2 = group2.country == "待识别照片"
            
            if isUnknown1 != isUnknown2 {
                return isUnknown1 // 未知照片优先显示
            }
            
            // 同类型内按照片数量排序
            return group1.totalPhotos > group2.totalPhotos
        }
        
        return groups
    }
    
    private func processKnownCityPhotos(_ photos: [PhotoData]) -> [LocationGroup] {
        var groups: [LocationGroup] = []
        
        // 按国家分组
        let countryGroups = Dictionary(grouping: photos) { photo in
            photo.location?.country ?? "未知国家"
        }
        
        for (country, countryPhotos) in countryGroups {
            // 按城市分组
            let cityGroups = Dictionary(grouping: countryPhotos) { photo in
                photo.location?.city ?? photo.location?.state ?? "未知城市"
            }
            
            for (city, cityPhotos) in cityGroups {
                // 创建城市父节点
                let cityGroup = LocationGroup(
                    country: country,
                    city: city,
                    detailedLocation: nil,
                    photos: cityPhotos.sorted { $0.creationDate > $1.creationDate },
                    coverPhoto: cityPhotos.first?.thumbnail,
                    totalPhotos: cityPhotos.count,
                    isParentNode: true,
                    parentCity: nil
                )
                groups.append(cityGroup)
                
                // 按详细地址创建子节点
                let detailedGroups = groupPhotosByDetailedLocation(cityPhotos)
                for (detailedLocation, detailedPhotos) in detailedGroups {
                    let detailedGroup = LocationGroup(
                        country: country,
                        city: city,
                        detailedLocation: detailedLocation,
                        photos: detailedPhotos.sorted { $0.creationDate > $1.creationDate },
                        coverPhoto: detailedPhotos.first?.thumbnail,
                        totalPhotos: detailedPhotos.count,
                        isParentNode: false,
                        parentCity: city
                    )
                    groups.append(detailedGroup)
                }
            }
        }
        
        return groups
    }
    
    private func processPhotosWithoutLocation(_ photos: [PhotoData]) -> [LocationGroup] {
        var groups: [LocationGroup] = []
        
        // 🎯 简化：删除"编码失败照片"分组，所有未知照片都归入"待识别照片"
        let allUnknownPhotos = photos.filter { photo in
            let hasGeocodingAttempted = photo.hasGeocodingAttempted ?? false
            let hasLocation = photo.location != nil
            
            // 没有位置信息，或者有位置信息但没有尝试过地理编码
            return !hasLocation || !hasGeocodingAttempted
        }
        
        // 🎯 优化：减少重复日志，只在分类数量发生变化时打印
        #if DEBUG
        if allUnknownPhotos.count != Self.lastUnknownCount2 {
            print("📍 [LocationGroupService] 无地理信息照片分类: 待识别=\(allUnknownPhotos.count)")
            Self.lastUnknownCount2 = allUnknownPhotos.count
        }
        #endif
        
        // 处理所有待识别的照片
        if !allUnknownPhotos.isEmpty {
            let unknownGroup = LocationGroup(
                country: "待识别照片",
                city: "待地理编码照片",
                detailedLocation: nil,
                photos: allUnknownPhotos.sorted { $0.creationDate > $1.creationDate },
                coverPhoto: allUnknownPhotos.first?.thumbnail,
                totalPhotos: allUnknownPhotos.count,
                isParentNode: true,
                parentCity: nil
            )
            groups.append(unknownGroup)
        }
        
        return groups
    }
    
    private func groupPhotosByDetailedLocation(_ photos: [PhotoData]) -> [String: [PhotoData]] {
        var groups: [String: [PhotoData]] = [:]
        
        for photo in photos {
            let detailedLocation = getDetailedLocationName(for: photo)
            if groups[detailedLocation] == nil {
                groups[detailedLocation] = []
            }
            groups[detailedLocation]?.append(photo)
        }
        
        return groups
    }
    
    private func getDetailedLocationName(for photo: PhotoData) -> String {
        guard let location = photo.location else {
            return "未知地点"
        }
        
        if let address = location.address, !address.isEmpty {
            return address
        }
        
        if let city = location.city, let state = location.state, city != state {
            return "\(city), \(state)"
        }
        
        if let city = location.city {
            return city
        }
        
        if let state = location.state {
            return state
        }
        
        return "未知地点"
    }
    
    private func calculateDataFingerprint(photos: [PhotoData]) -> String {
        let photoCount = photos.count
        let photosWithLocation = photos.filter { $0.location != nil }.count
        let photosWithoutLocation = photos.filter { $0.location == nil }.count
        
        // 计算有完整地理信息的照片数量（国家和城市都有明确信息）
        let photosWithCompleteLocation = photos.filter { photo in
            guard let location = photo.location else { return false }
            let hasCountry = location.country != nil && location.country != "未知国家"
            let hasCity = location.city != nil && location.city != "未知城市"
            let hasValidState = location.state == nil || (location.state != nil && location.state != "未知州")
            
            return hasCountry && hasCity && hasValidState
        }.count
        
        // 计算有地理编码尝试的照片数量
        let geocodedPhotos = photos.filter { $0.hasGeocodingAttempted == true }.count
        
        // 🚀 修复：移除不稳定的地址信息统计，只使用稳定的基础信息
        // 原来的photosWithAddress会在解析过程中不断变化，导致指纹不稳定
        // 现在只使用照片总数、有位置信息的照片数、无位置信息的照片数等稳定信息
        
        return "\(photoCount)_\(photosWithLocation)_\(photosWithoutLocation)_\(photosWithCompleteLocation)_\(geocodedPhotos)"
    }
    
    private func updateCache(groups: [LocationGroup], photos: [PhotoData]) {
        cachedGroups = groups
        lastPhotoCount = photos.count
        lastDataFingerprint = calculateDataFingerprint(photos: photos)
        
        // 🚀 性能优化：减少开机日志，只在调试模式或大量照片时打印
        #if DEBUG
        if photos.count > 1000 {
            print("📍 [LocationGroupService] 缓存已更新: 分组数=\(groups.count), 照片数=\(photos.count)")
        }
        #endif
    }
    
    private func clearCache() {
        cachedGroups = []
        lastPhotoCount = 0
        lastDataFingerprint = ""
        print("📍 [LocationGroupService] 缓存已清空")
    }
    
    private func saveToPersistence(_ groups: [LocationGroup]) {
        // 先创建父节点ID映射
        let parentNodeIds = groups.filter { $0.isParentNode }.map { $0.id }
        
        let serializableGroups = groups.map { group in
            var groupData: [String: Any] = [
                "id": group.id,
                "country": group.country,
                "city": group.city,
                "detailedLocation": group.detailedLocation ?? "",
                "totalPhotos": group.totalPhotos,
                "isParentNode": group.isParentNode
            ]
            
            // 对于子节点，使用父节点的ID而不是字符串
            if !group.isParentNode, let parentCity = group.parentCity {
                // 查找对应的父节点ID
                if let parentGroup = groups.first(where: { $0.isParentNode && $0.city == parentCity }) {
                    groupData["parentId"] = parentGroup.id
                } else {
                    // 如果找不到父节点，使用空字符串
                    groupData["parentId"] = ""
                }
            } else {
                groupData["parentId"] = ""
            }
            
            return groupData
        }
        
        if let data = try? JSONSerialization.data(withJSONObject: serializableGroups) {
            UserDefaults.standard.set(data, forKey: locationGroupsKey)
            // 🚀 性能优化：减少开机日志，只在调试模式或大量照片时打印
        #if DEBUG
        if groups.count > 10 {
            print("📍 [LocationGroupService] 分组已保存到持久化: \(groups.count) 个分组")
        }
        #endif
        }
    }
} 